package com.xxgc.eow.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xxgc.eow.utils.CosFile;
import com.xxgc.eow.utils.CosUtils;
import com.xxgc.eow.utils.HttpClientUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import com.xxgc.eow.result.Result;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.xxgc.eow.service.IUserService;
import com.xxgc.eow.entity.User;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Mr.Abel
 * @since 2023-05-20
 */
@Tag(name = "用户表")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 查询所有接口
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "查询所有接口", description = "查询用户表所有数据")
    @SaIgnore
    @GetMapping
    public Result<List<User>> findAll() {
        return Result.ok(userService.selectAll());
    }

    /**
     * 根据id查询数据接口
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "根据id查询数据接口", description = "通过组件id查询")
    @Parameters({
            @Parameter(name = "id",description = "组件id",required = true,in=ParameterIn.QUERY)
    })
    @SaIgnore
    @GetMapping("/{id}")
    public Result<User> findOne(@PathVariable Integer id) {
        return Result.ok(userService.getById(id));
    }

    /**
     * 根据keyWord查询数据接口
     * @param keyWord
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "根据keyWord查询数据接口", description = "根据keyWord查询数据接口")
    @Parameters({
            @Parameter(name = "keyWord",description = "keyWord",required = true,in=ParameterIn.QUERY)
    })
    @SaIgnore
    @GetMapping("/byKeyWord")
    public Result<List<User>> getBykeyWord(@RequestParam String keyWord) {
        return Result.ok(userService.getByKeyWord(keyWord));
    }

    /**
     * 分页查询接口
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "分页查询接口", description = "分页查询")
    @Parameters({
            @Parameter(name = "pageNum",description = "页码",example="1",required = true,in=ParameterIn.QUERY),
            @Parameter(name = "pageSize",description = "每页多少条",example="10",required = true,in=ParameterIn.QUERY)
    })
    @SaIgnore
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return Result.ok(userService.selectAll());
    }

    /**
     * 新增和更新接口
     * @param
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "新增和更新接口", description = "传入id为更新,不传为新增,时间和有效字段均不填")
    @SaIgnore
    @PostMapping
    public Result save(@RequestBody User user) {
        userService.saveOrUpdate(user);
        return Result.ok();
    }

    /**
     * 删除接口
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "删除接口", description = "通过id删除")
    @Parameters({
            @Parameter(name = "id",description = "组件id",required = true,in=ParameterIn.QUERY)
    })
    @SaIgnore
    @DeleteMapping("del/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.ok();
    }

    /**
     * 批量删除接口
     * @param ids
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "批量删除接口", description = "批量删除接口")
    @SaIgnore
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        userService.removeByIds(ids);
        return Result.ok();
    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "用户通过手机号登录", description = "用户通过手机号登录接口")
    @PostMapping("/login")
    public Result userLogin(@Parameter String telephone,@Parameter String password){
        User user = userService.userLogin(telephone,password);
        System.out.println(user);
        if (user!=null){
            return new Result<>(200,"登陆成功",user);
        }else{
            return new Result<>(400,"登陆失败","密码或用户名错误了哟！");
        }

    }


    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "用户通过手机号注册", description = "用户通过手机号注册接口")
    @PostMapping("/registration")
    public Result userRegister(@Parameter String telephone,@Parameter String password){
        int tf = userService.insertUser(telephone,password);
        if (tf==1){
            return new Result<>(200,"注册成功");
        }else{
            return new Result<>(400,"注册失败","手机号已被注册！");
        }

    }

    /**
     * 登录接口
     * @return
     */
    @ApiOperationSupport(author = "yxh")
    @Operation(summary = "用户登录接口", description = "用户登录接口")
    @SaIgnore
    @GetMapping("/login")
    public Result<User> userLoginByName(String username,String password) {
        User user = new User();
        user.setUserName(username);
        userService.getUserByNameAndPass(user);
        if(userService.getUserByNameAndPass(user) == null){
            user.setUserName(null);
            user.setNickname(username);
            if(userService.getUserByNameAndPass(user) == null){
                return Result.error("用户名不存在");
            }else{
                user.setUserPassword(password);
                if(userService.getUserByNameAndPass(user) != null){
                    return Result.ok(userService.getUserByNameAndPass(user));
                }
            }
        }else {
            user.setUserName(null);
            user.setNickname(username);
            if(userService.getUserByNameAndPass(user) == null){
                user.setUserName(username);
                user.setNickname(null);
            }
            user.setUserPassword(password);
            if(userService.getUserByNameAndPass(user) != null){
                return Result.ok(userService.getUserByNameAndPass(user));
            }
        }
        return Result.error("密码错误");
    }

    /**
     * 注册
     * @return
     */
    @ApiOperationSupport(author = "yxh")
    @Operation(summary = "用户注册接口", description = "用户注册接口")
    @SaIgnore
    @PostMapping("/register")
    public Result userRegisterByName(@RequestBody Map<String, String> map) {
        String userName = map.get("userName");
        String userPassword = map.get("userPassword");
        String rePassword = map.get("rePassword");
        User user = new User();
        if("微信用户".equals(userName)){
            userName += System.currentTimeMillis();
        }
        user.setUserName(userName);
        if(user.getUserName() == null || user.getUserName() == ""){
            return Result.error(1001,"用户名为空","");
        }
        if(userPassword == null || userPassword == ""){
            return Result.error(1002,"密码为空","");
        }
        if(rePassword == null || rePassword == ""){
            return Result.error(1003,"再次输入的密码为空","");
        }
        if(!userPassword.equals(rePassword)){
            return Result.error(1004,"两次密码不一致","");
        }
        if(userService.getUserByNameAndPass(user) != null){
            return Result.error(1005,"用户名已经存在","");
        }else{
            user.setUserPassword(userPassword);
            user.setNickname(user.getUserName());
            user.setUserRegister(LocalDate.now());
            user.setBirthday(LocalDate.now().plusDays(1));
            user.setUserUrl("https://img2.baidu.com/it/u=3383096564,177795970&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500");
            user.setSex("男");
            user.setTelephone("暂无手机号");
            user.setPersonalProfile("暂无简介");

            userService.save(user);
            return Result.ok(user.getUserName());
        }
    }

    /**
     * 修改头像
     * @return
     */
    @ApiOperationSupport(author = "yxh")
    @Operation(summary = "修改/上传头像", description = "用户修改/上传头像接口")
    @SaIgnore
    @PostMapping("/update/headImg")
    @ResponseBody
    public Result userUpdateHead(Integer userId,MultipartFile file) throws IOException {
        User user = userService.getById(userId);
        user.setUserUrl(CosUtils.uploadFile(file,"images/heads/"));
        save(user);
        return Result.ok(user.getUserUrl());
    }

    /**
     * 获取用户openid
     * @return
     */
    @ApiOperationSupport(author = "yxh")
    @Operation(summary = "获取用户openid", description = "获取用户openid接口")
    @SaIgnore
    @GetMapping("/getOpenIdForCloud")
    public Result getOpenIdForCloud(String code) {
        String str = HttpClientUtils.doGet("https://api.weixin.qq.com/sns/jscode2session","appid=wx0a0f6f7a6a77d125&secret=7204f5c9983d656c9338798d39c6a221&js_code="+code+"&grant_type=authorization_code");
        if(str.contains("errmsg")){
            return Result.error("查询失败");
        }
        return Result.ok(str);
    }
}